package com.ctfo.ulcp.exp.core;

import org.graalvm.polyglot.*;

public class SecurePolyglotExample {

    public static void main(String[] args) {
        // 创建具有限制权限的Python环境
        try (Context context = Context.newBuilder("python")
                .allowIO(false) // 禁止IO操作
                .allowCreateThread(false)
                .allowHostAccess(true)
                .build()) {

            // 尝试在Python代码中执行IO操作，应该会失败
            try {
                context.eval("python", "open('test.txt', 'w').write('hello')");
            } catch (Exception e) {
                System.out.println("Caught exception as expected: " + e.getMessage());
            }

            // 执行其他Python代码，例如调用Java方法
            String code = """
                    import java
                    import json
                    print(dir(json))
                    engine = java.type('com.ctfo.ulcp.exp.utils.PythonCodeEngine')
                    result = engine.sayHello('Python user')
                    print(result)
                    result
                    """;
            context.eval("python", code);
        }

        // Java代码可以继续进行IO操作
        try {
            java.nio.file.Files.write(java.nio.file.Paths.get("test_java.txt"), "Hello from Java".getBytes());
            System.out.println("Java IO operation succeeded.");
        } catch (Exception e) {
            System.out.println("Unexpected exception: " + e.getMessage());
        }
    }
}
